package com.imooc.exception;


import com.imooc.grace.result.GraceJSONResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;

@ControllerAdvice
public class GraceExceptionHandler {


    @ExceptionHandler(MyCustomException.class)
    @ResponseBody
    public GraceJSONResult returnMyCustomException(MyCustomException e){
        e.printStackTrace();
        return GraceJSONResult.exception(e.getResponseStatusEnum());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public GraceJSONResult returnNotValid(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        HashMap<String, String> errors = getErrors(bindingResult);
        return GraceJSONResult.errorMap(errors);
    }


    public HashMap<String, String> getErrors(BindingResult result){
        List<FieldError> errorList = result.getFieldErrors();
        HashMap<String, String> map = new HashMap<>();
        for (FieldError fieldError : errorList) {
            //获取错误信息
            String defaultMessage = fieldError.getDefaultMessage();
            //错误所对应的属性字段名
            String field = fieldError.getField();
            map.put(field,defaultMessage);
        }

        return map;
    }
}
